/** 请求方法
 * @param {Object} method 方式
 * @param {Object} url      路径
 * @param {Object} param  参数
 * @param {Object} that   当前页面
 */
function request(method, url, param, that) {
    that.show_loading = true
    url = that.$config.domain.api + url
    method = method.toUpperCase()
    var user = uni.getStorageSync('user');
    if (!user) {
        user = {token: ''}
    }
    console.log(param)
    return new Promise((resolve, reject) => {
        let options = {
			header: {
				'token':user.token,
				'Content-Type':'application/json'
			},
            url: url,
            data: param,
            method: method,
            success: (res) => {
                console.log(res)
                that.show_loading = false
                resolve(res)
                uni.stopPullDownRefresh();
                uni.hideLoading()
                if (res.data.code == 401) {
                    uni.redirectTo({
                        url: '/pages/user/login'
                    })
                } else if (res.data.code == 422) {
                    that.$util.toast(res.data.message)
                }
            },
            fail: (err) => {
                that.show_loading = false
                uni.stopPullDownRefresh();
                uni.hideLoading()
                var msg = '网络错误，请联系管理员！'
                that.$util.toast(msg)
                reject(msg);
            }
        }
        if (options.url && options.method) {
            uni.request(options);
        }
    })
}

/**
 * @param {Object} url        请求路径
 * @param {Object} parm        请求参数
 * @param {Object} file        上传文件
 * @param {Object} success    成功回调
 */
function upload_img(that, url, parm, file, success) {
    console.log(parm)
    that.show_loading = true

    var user = uni.getStorageSync('user');
    uni.uploadFile({
        url: that.$config.domain.api_img + url, //仅为示例，非真实的接口地址
        filePath: file,
        name: "file",
        formData: parm,
        header: {
            'Authorization': user.token,
            'Accept': 'appliction/json',
            'Content-Type': 'application/json'
        },
        method: 'POST',
        //成功
        success: function (res) {
            var data = JSON.parse(res.data)
            success(data);
            if (data.code == 0) {
                that.$util.toast('图片上传成功')
            }
            that.show_loading = false
            uni.hideLoading()
        },
        //失败
        fail: function (res) {
            that.show_loading = false
            uni.hideLoading()
        },
        //完成
        complete: function (e) {
            that.show_loading = false
            uni.hideLoading()
        },
    });
}

export default {
    req: request,
    upload: upload_img
}
